package com.zsy.oauth2.config;

import com.zsy.oauth2.config.dto.CustomUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**是方法是为了token扩展额外的信息，也就是让jwt包含其他信息
 * @ClassName CustomUserAuthenticationConverter
 * @Description TODO
 * @Author zhaoshouyun
 * @Date 2020/4/20 21:59
 * @Version 1.0
 */
@Component
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        LinkedHashMap response = new LinkedHashMap();
        response.put("user_name", authentication.getName());

        Object principal = authentication.getPrincipal();
        if (principal instanceof CustomUser ){
            CustomUser customUser = (CustomUser) principal;
            response.put("name",customUser.getName());
            response.put("id", customUser.getId());
            response.put("otherUserInfoValue",customUser.getOtherUserInfoParam());
          //  response.put("createAt", ((User) authentication.getPrincipal()).getCreateAt());
        }
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }

        return response;
    }
}
